<?php

namespace App\Http\Controllers\Web\V1;

use App\Models\Question;
use App\Models\Redo;
use App\Models\User;
use App\Models\Integral;
use Carbon\Carbon;
use Dingo\Api\Http\Response;
use Illuminate\Http\Request;
use App\Models\StudentResult;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class CorrectController extends Controller
{
    /**
     * 考试试卷提交
     *
     * @param StudentResult $studentResult
     * @param Request $request
     * @return Response
     */
    public function index(StudentResult $studentResult, Request $request)
    {
        // 用户得分
        $fraction = 0;
        // 用户正确题数
        $successNum = 0;
        // 用户答题数
        $alreadyNum = count($request->input('data'));
        // 正确答案id数组
        $successIds = [];
        // 错误答案id数组
        $errorIds = [];
        // 错题库数据
        $data = [];
        //现在时间
        $now = Carbon::now();
        //当前月第一天
        $firstDay = $now->startOfMonth()->toDateTimeString();
        //当前最后一天
        $lastDay = $now->endOfMonth()->toDateTimeString();

        // 如果用户答题数大于本章试卷总题数
        if ($alreadyNum > $studentResult->all_num) {
            return $this->response->error('参数错误', 422);
        }

        $userId = auth()->id();

        // 计算用户正确题目数量和总得分
        foreach ($request->input('data') as $value) {
            if ($value['is_true']) {
                $successNum += 1;
                $fraction += $value['fraction'];
                array_push($successIds, $value['id']);
            } else {
                array_push($errorIds, $value['id']);
                // 错题库数据
                array_push($data, ['user_id' => $userId, 'question_id' => $value['id'], 'answer' => $value['answer'], 'type' => $value['type']]);
            }
        }

        $integral['examination_id'] = $studentResult->examination_id;
        $integral['user_id'] = $studentResult->user_id;
        $integral['this_integral'] = 10;
        $integral['get_time'] = date('Y-m-d H:i:s');

        $timer = strtotime(date(now())) - strtotime($studentResult->created_at);

        try {
            DB::beginTransaction();
            // 更新content字段
            $studentResult->content = $request->input('data');
            // 更新分数字段
            $studentResult->fraction = $fraction;
            // 更新正确题目数量
            $studentResult->success_num = $successNum;
            // 更新用户答题数量
            $studentResult->already_num = $alreadyNum;
            // 更新用户错误题数
            $studentResult->error_num = $studentResult->all_num - $successNum;
            // 更新用户考试用时
            $studentResult->timer = $timer;
            // 更新用户交卷时间
            $studentResult->end_time = date(now());
            // 更新提交类型字段
            $studentResult->submit_type = 0;

            $studentResult->save();

            Question::query()
                ->whereIn('id', $successIds)
                ->increment('success_num');

            Question::query()
                ->whereIn('id', $errorIds)
                ->decrement('error_num');

            Integral::create($integral);

            //如果是本日的，判断交卷时间是否在本日，那么day_integral字段就自增10
            if (Carbon::parse($studentResult->end_time)->between(Carbon::today(), Carbon::tomorrow(), false)) {
                User::query()
                ->where('id', $studentResult->user_id)
                ->increment('day_integral', 10);
            }

            //如果是本周的，判断交卷时间是否在本周，那么week_integral字段就自增10
            if (Carbon::parse($studentResult->end_time)->between(Carbon::parse('last monday'), Carbon::parse('sunday'), false)) {
                User::query()
                    ->where('id', $studentResult->user_id)
                    ->increment('week_integral', 10);
            }

            //如果是本月的，判断交卷时间是否在本月，那么month_integral字段就自增10
            if (Carbon::parse($studentResult->end_time)->between($firstDay, $lastDay, false)) {
                User::query()
                    ->where('id', $studentResult->user_id)
                    ->increment('month_integral', 10);
            }

            foreach ($data as $value) {
                Redo::query()
                    ->updateOrInsert(
                        ['user_id' => $value['user_id'], 'question_id' => $value['question_id']],
                        ['answer' => $value['answer']]
                    );
            }

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            report($exception);
            return $this->response->error('参数错误', 422);
        }

        return $this->response->noContent();
    }
}
